import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Select, TreeSelect, DatePicker, Checkbox, message, Dropdown, Menu, Icon, Modal, Upload } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, confirmDelete, getYear, getNameByState, tableWidth, statistics, backUrl, renderExt } from 'lib/fun'
import EditAuditor from './components/editOrgAuditor'
import SubmitingUser from './components/submitingUser'
import FilterModule from './components/filterProjectJustUserAtOrg'
import CopyBatchData from './components/copyBatchData'
import CreateSubmiting from './components/createSubmiting'
import BarInfo from 'components/barInfo'

const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const { RangePicker } = DatePicker;
const Option = Select.Option;

class ModuleName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      data: [],
      selectedRowKeys: [],
      projectList: [],
      visible: false,
      editType: "",
      rowdata: {},
      rowdata2: {},
      visible2: false,
      createVisable: false,
      createType: 1,
      copyBatchDataVisible: false,
      showBar: false,
      barId: "",
      typeId: "",
    }
    this.current = 1;   //当前第几页
    this.total = 0;   //总共多少页
    this.pageSize = 10;   //每页多少行
    this.search = {};
  }

  componentDidMount(){
    const { config, addConfig } = this.props;
    // load 项目列表
    this.loadProject();
    // citizen_info_type_code  人员分类没有找着
    this.loadData();
    if(!config.payObjCode){
      // 发放对象
      addConfig('payObjCode',10);
    }
    if(!config.payCycleCode){
      // 发放周期
      addConfig('payCycleCode',9);
    }
  }

  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(((this.current-1)*this.pageSize+1)/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }

  loadProject = ()=>{
    var self = this;
    Ajax({
      url: '/project/list',
      data: {
        perPage: 10000,   //每页数量
      },
      success: function(data){
        self.setState({
          projectList: data.list
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  loadData = () => {
    var self = this;
    self.setState({
      loading: true
    });
    Ajax({
      url: '/projectRegister/orgAuditorList',
      data: Object.assign({}, this.search, {
        currentPage: self.current, 
        perPage: self.pageSize
      }),
      success: function(data){
        self.total = data.totalCount;
        self.setState({
          loading: false,
          data: data.list
        });
      },
      error: function(error){
        self.setState({
          loading: false
        });
        message.error(error);
      }
    });
  }

  handleFilter = (option)=>{
    if(!_.isEqual(option, this.search)){
      this.search = option;
      this.loadData();
    }
  }

  // 操作
  operate = (row)=>{
    this.setState({
      visible: true,
      rowdata: row
    });
  }

  renderContent = ()=>{
    return <Input id="reason" type="textarea"/>
  }

  // 复核
  approvalSubmit = (auditorType, batchId)=>{
    var self = this;
    var fun = (reason)=>{
      Ajax({
        url: '/projectRegister/orgAuditorApproval',
        data: {
          batchId,
          auditorType,
          reason: reason?reason:undefined
        },
        success: function(data){
          if(auditorType == 1){
            var find = _.find(self.state.data, function(d) {
              return d.batchId == batchId
            });
            find.state = 60;
          }else{
            _.remove(self.state.data, function(d) {
              return d.batchId == batchId
            });
          }
          self.setState({
            data: self.state.data
          });
        },
        error: function(error){
          message.error(error);
        }
      });
    }
    if(auditorType==2){
      Modal.confirm({
        title: '确定打回请填写理由',
        content: self.renderContent(),
        onOk() {
          return new Promise((resolve, reject) => {
            var reason = document.getElementById('reason').value;
            fun(reason);
            resolve();
          }).catch(() => console.log('Oops errors!'));
        },
        onCancel() {},
      });
    }else{
      confirmDelete(()=>{
        fun()
      }, ()=>{
        message.info('取消操作');
      }, auditorType==3?'确认提交上报？':'确定要审批通过吗？');
    }
  }
  // 汇总上报
  orgAuditorSubmit = ()=>{
    var self = this;
    confirmDelete(()=>{
      self.setState({
        loading: true
      });
      Ajax({
        url: '/projectRegister/orgAuditorSubmit',
        data: {
          batchIds: this.state.selectedRowKeys,
          auditorType: 3
        },
        success: function(data){
          self.current = 1;
          self.loadData();
          self.setState({
            loading: false,
            selectedRowKeys: []
          });
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消操作');
    },'确认提交上报吗？');
  }

  operate2 = (type, row, num)=>{
    if(num&&num>0){
      this.setState({
        visible2: true,
        editType: type,
        rowdata2: row
      });
    }
  }

  editOk = (b)=>{
    this.setState({
      visible:false
    })
    b&&this.loadData()
  }

  // 转结
  copyBatchData = (row)=>{
    this.setState({ 
      copyBatchDataVisible: true,
      rowdata: row
    })
  }
  onCopyOk = (b)=>{
    this.setState({
      copyBatchDataVisible: false
    });
    b&&(this.current = 1)&&this.loadData();
  }
  // 新增
  batchAppend = (row)=>{
    this.setState({ 
      createVisable: true,
      createType: 3,
      rowdata: row,
    })
  }
  // 删除
  doDelete = (batchId)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/projectRegister/deleteRegisterBatch',
        data: {
          batchId
        },
        success: function(data){
          // _.remove(self.state.data, function(d) {
          //   return d.batchId == batchId
          // });
          // self.setState({
          //   data: self.state.data
          // });
          self.loadData();
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消操作');
    }, '确定要删除吗？');
  }
  
  onShowBar = (obj)=>{
    this.setState(Object.assign({
      showBar: true
    }, obj));
  }

  // 导入
  onExport = (b)=>{
    this.setState({ 
      showBar: false 
    })
    b&&(this.current = 1)&&this.loadData();
  }

  // 修改
  onEdit = (b)=>{
    this.setState({ 
      visible2: false 
    })
    b&&this.loadData();
  }

  render() {
    var self = this;
    const { config, common } = this.props;
    const columns = [{
      title: '批次ID',
      dataIndex: 'batchId'
    }, {
      title: '项目编号',
      dataIndex: 'projectId'
    }, {
      title: '项目名称',
      dataIndex: 'projectName'
    }, {
      title: '补贴年度',
      dataIndex: 'year'
    }, {
      title: '发放周期',
      dataIndex: 'payCycleCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'payCycleCode', text) }</span>)
    }, {
      title: '发放次数',
      dataIndex: 'subsidyCount'
    }, {
      title: '补贴登记区划',
      dataIndex: 'areaName'
    }, {
      title: '发放对象',
      dataIndex: 'payObjCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'payObjCode', text) }</span>)
    }, {
      title: '总登记成功人数',
      dataIndex: 'totalCount',
      render: (text, record) => (<span><a href="javascript:;" title="查看详情" onClick={this.operate2.bind(this, 'total', record, text)}>{text?text:0}</a></span>)
    }, {
      title: '成功人数',
      dataIndex: 'successCount',
      render: (text, record) => (<span><a href="javascript:;" title="查看详情" onClick={this.operate2.bind(this, 'success', record, text)}>{text?text:0}</a></span>)
    }, {
      title: '成功金额',
      dataIndex: 'successMoney'
    }, {
      title: '失败人数',
      dataIndex: 'failCount',
      render: (text, record) => (<span><a href="javascript:;" title="查看详情" onClick={this.operate2.bind(this, 'fail', record, text)}>{text?text:0}</a></span>)
    }, {
      title: '失败原因',
      dataIndex: 'failReason'
    }, {
      title: '状态',
      dataIndex: 'state',
      fixed: 'right',
      render: (text, record) => (<span>{ getNameByState(common, "projectRegisterBatchEn", text) }</span>)
    }, {
      title: '扩展属性',
      dataIndex: 'extStatList',
      render: (text, record) => (<span>{ renderExt(text) }</span>)
    }, {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      render: (text, record) => record.state == 50?(<Dropdown overlay={      
            <Menu>
              <Menu.Item>
                <a onClick={this.operate.bind(this, record)} href="javascript:;">审批人员</a>
              </Menu.Item>
              <Menu.Item>
                <a onClick={this.approvalSubmit.bind(this, 1, record.batchId)} href="javascript:;">批次审批通过</a>
              </Menu.Item>
              {record.creatorUserType!='common'?<Menu.Item>
                  <a onClick={this.approvalSubmit.bind(this, 2, record.batchId)} href="javascript:;">打回</a>
                </Menu.Item>:""
              }
              {record.creatorUserType=='common'?<Menu.Item>
                  <a onClick={this.batchAppend.bind(this, record)} href="javascript:;">新增</a>
                </Menu.Item>:""
              }
              {record.creatorUserType=='common'?<Menu.Item>
                  <a onClick={this.copyBatchData.bind(this, record)} href="javascript:;">结转</a>
                </Menu.Item>:""
              }
              {record.creatorUserType=='common'?<Menu.Item>
                  <a onClick={this.doDelete.bind(this, record.batchId)} href="javascript:;">删除</a>
                </Menu.Item>:""
              }
              {record.creatorUserType=='common'&&record.registerFailCount&&record.registerFailCount>0?<Menu.Item>
                  <a onClick={this.operate2.bind(this, 'rFail', record, record.registerFailCount?record.registerFailCount:0)} href="javascript:;">登记失败人员</a>
                </Menu.Item>:""
              }
            </Menu>
      }>
        <a className="ant-dropdown-link" href="javascript:;">
          操作 <Icon type="down" />
        </a>
      </Dropdown> ):""
    }];

    var width = tableWidth(columns);

    var pagination = {
      current: this.current,
      total: this.total,
      pageSize: this.pageSize,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        self.setState({
          selectedRowKeys: selectedRowKeys
        });
      },
      selectedRowKeys: this.state.selectedRowKeys,
      getCheckboxProps: record => ({
        disabled: record.state == 50,    // Column configuration not to be checked
      }),
    };

    const props = {
      name: 'file',
      multiple: false,
      showUploadList: false,
      action: backUrl("/projectRegister/uploadCitizen"),
      data: {},
      onChange(info) {
        const status = info.file.status;
        if (status == 'uploading') {
          self.setState({
            showBar: true
          });
        }
        if (status === 'done') {
          var result = info.file.response;
          // &&result.data.successCount&&result.data.successCount>0
          if(result.status == 1&&result.data){
            const data = result.data
            self.setState({
              showBar: true,
              barId: data.barId,
              typeId: data.typeId,
            });
          }else{
            notification.error({
              message: '文件上传失败',
              description: result.msg||"未知失败原因",
              duration: 60,
            });
            self.setState({
              showBar: false
            });
          }
        } else if (status === 'error') {
          message.error("文件上传失败");
          self.setState({
            showBar: false
          });
        }
      },
    };

    const content = (
      <Menu>
        <Menu.Item>
          <a href="javascript:;" onClick={()=>{
            this.setState({ createVisable: true, createType: 1 })
          }}>导出填报表</a>
        </Menu.Item>
        <Menu.Item>
          <Upload {...props}>
            <a href="javascript:;" style={{color: '#666'}}>导入填报表</a>
          </Upload>
        </Menu.Item>
      </Menu>
    );

    return (
      <div className="area projectRegister">
        <FilterModule 
          handleFilter={ this.handleFilter }
          projectList={ this.state.projectList }
        />
        <div className="area-con">
          <Table 
            columns={columns}
            dataSource={this.state.data}
            pagination={pagination}
            rowKey="batchId"
            loading={ this.state.loading }
            rowSelection={ rowSelection }
            footer={ ()=> statistics(this.state.data) }
            scroll={{ x: width, y: false }}
            title={() => (<div>
                            <Button 
                              type="primary"
                              style={{marginRight: 10}} 
                              disabled={ this.state.selectedRowKeys.length <= 0 }
                              onClick={ this.orgAuditorSubmit }
                            >
                              汇总上报
                              {
                                this.state.selectedRowKeys.length>0?(<span>({this.state.selectedRowKeys.length})</span>):""
                              }
                            </Button>
                            <Button 
                                type="primary" 
                                style={{marginRight: 10}} 
                                icon="edit" 
                                onClick={()=>this.setState({ createVisable: true, createType: 2 })}
                              >新建</Button>
                              <Dropdown overlay={content}>
                                <Button type="primary" icon="export">报表导入</Button>
                              </Dropdown>
                            </div>)}
          />
        </div>
        <EditAuditor
          visible={ this.state.visible }
          batchId = { this.state.rowdata.batchId }
          onClose={ this.editOk }
          type="orgAuditorRegisterList"
          see={true}
        />
        <SubmitingUser
          visible={this.state.visible2}
          onClose={this.onEdit}
          type={ this.state.editType }
          batchId = { this.state.rowdata2.batchId }
          see={ this.state.rowdata2.creatorUserType=='common'?false:true }
          successDown={ true }
        />
        <CopyBatchData
          visible={this.state.copyBatchDataVisible}
          onClose={this.onCopyOk}
          rowdata = { this.state.rowdata }
        />
        <CreateSubmiting
          visible={this.state.createVisable}
          onClose={()=>this.setState({ createVisable: false })}
          roleType="org"
          type={this.state.createType}
          rowdata={ this.state.rowdata }
          treeData={this.state.treeData}
          onShowBar={this.onShowBar}
        />
        <BarInfo
          visible={this.state.showBar}
          barId={this.state.barId}
          typeId={this.state.typeId}
          onClose={this.onExport}
        />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(ModuleName)